// import { LocalUploader } from '../extensions/file/local-uploader';
import { AuthFailed, Failed } from 'lin-mizar';
import util from 'util';
import axios from 'axios';
import { config } from 'lin-mizar/lin/config';
// import { Auth } from '../middleware/auth';

// import jwt from 'jsonwebtoken';
class WXManager {
  constructor () {
    this.appId = config.getItem('wx.appId');
    this.secretKey = config.getItem('wx.appSecret');
  }

  static async codeToUserIdAndKey (code) {
    const url = util.format(config.getItem('wx.loginUrl'),
      config.getItem('wx.appId'),
      config.getItem('wx.appSecret'),
      code);

    const result = await axios.get(url);
    if (result.status !== 200) {
      throw new AuthFailed({ message: 'openid获取失败' });
    }
    const errcode = result.data.errcode;
    const errmsg = result.data.errmsg;
    if (errcode) {
      throw new AuthFailed({
        errorCode: errcode,
        message: 'openid获取失败:' + errmsg
      });
    }
    return {
      openid: result.data.openid,
      sessionKey: result.data.session_key
    };
  }

  // 校验信息是否合法
  async msgSecCheck (content) {
    const accessToken = await this.getAccessToken();
    if (accessToken) {
      const result = await axios.post(`https://api.weixin.qq.com/wxa/msg_sec_check?access_token=${accessToken}`, { content });
      if (result.status !== 200) {
        throw new AuthFailed({ message: '内容安全识别失败' });
      }
      const data = result.data;
      if (data.errcode !== 0) {
        throw new Failed({ message: '含有违法违规内容,请编辑后重新发送' + data.errmsg });
      }
    }
  }

  async getAccessToken () {
    const result = await axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.appId}&secret=${this.secretKey}`);
    if (result.status !== 200) {
      throw new AuthFailed({ message: 'access_token获取失败' });
    }
    const data = result.data;
    if (data.access_token) {
      return data.access_token;
    } else {
      return false;
    }
  }
}

// const generateToken = function (uid, scope) {
//   const secretKey = config.getItem('security.secretKey');
//   const expiresIn = config.getItem('security.expiresIn');
//   const token = jwt.sign({
//     uid,
//     scope
//   }, secretKey, {
//     expiresIn
//   });
//   return token;
// };

module.exports = {
  WXManager
};